package com.ktg.mes.chanjet.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chanjet.openapi.sdk.java.ChanjetClient;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.Result;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.chanjet.common.Constants;
import com.ktg.mes.chanjet.config.OpenApiConfig;
import com.ktg.mes.chanjet.content.QueryOrdersContent;
import com.ktg.mes.chanjet.request.OrderSeachsRequest;
import com.ktg.mes.chanjet.response.GetVoucherResponse;
import com.ktg.mes.chanjet.response.InventoryClassResponse;
import com.ktg.mes.chanjet.response.OrderSeachsResponse;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.chanjet.vo.QueryOrderVo;
import com.ktg.mes.md.domain.MesScalesOrderItem;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.mes.md.service.IMesScalesOrderService;
import com.ktg.mes.unit.other.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("/chanjet/order")
@Api(tags = "开放平台订单管理")
public class ChanjetOrderController extends BaseController {

    @Autowired
    private ChanjetClient chanjetClient;


    @Autowired
    private OpenApiConfig config;


    @Autowired
    private RedisService redisService;

    @Autowired
    private ChanjetSpi chanjetSpi;


    @Autowired
    private IMesScalesOrderService iMesScalesOrderService;


    @Autowired
    private IMesScalesOrderItemService iMesScalesOrderItemService;

    @PostMapping("/queryOrders")
    @ApiOperation("查询订单")
    public Result<Object> queryOrders(@RequestBody QueryOrderVo vo) throws ChanjetApiException {
        OrderSeachsRequest orderSeachsRequest = new OrderSeachsRequest();
        orderSeachsRequest.setAppKey(config.getAppKey());
        orderSeachsRequest.setOpenToken(redisService.get(Constants.CHANJET_TOKEN));
        orderSeachsRequest.setAppSecret(config.getAppSecret());
        orderSeachsRequest.setRequestUri("/financial/order/searchOrders");
        orderSeachsRequest.setContentType("application/json");
        JSONObject queryParams = new JSONObject();
        if(StringUtils.isNotEmpty(vo.getOrderNo())){
            queryParams.putOpt("orderNo",vo.getOrderNo());
        }
        if(StringUtils.isNotEmpty(vo.getPayTimeFrom())){
            queryParams.putOpt("payTimeFrom",vo.getPayTimeFrom());
        }
        if(StringUtils.isNotEmpty(vo.getPayTimeTo())){
            queryParams.putOpt("payTimeTo",vo.getPayTimeTo());
        }
        QueryOrdersContent queryOrdersContent = new QueryOrdersContent();
        queryOrdersContent.setRows(vo.getRows());
        queryOrdersContent.setStart(vo.getStart());
        queryOrdersContent.setSearchOrderParam(queryParams);
        orderSeachsRequest.setBizContent(queryOrdersContent);
        OrderSeachsResponse orderSeachsResponse = chanjetClient.execute(orderSeachsRequest);
        if(!orderSeachsResponse.getResult().equals("true")){
            return Result.ERROR("获取订单失败");
        }
        OrderSeachsResponse.Value value = orderSeachsResponse.getValue();
        return Result.OK(value);
    }

    @PostMapping("/getVoucher")
    @ApiOperation("查询销售订单")
    public Result<Object> GetVoucher(@RequestBody QueryOrderVo vo) throws ChanjetApiException {
        return Result.OK(chanjetSpi.getVoucherOrder(vo).getData());
    }


    @PostMapping("/list")
//    @PreAuthorize("@ss.hasPermi('tplus:order:list')")
    @ApiOperation("销售订单列表")
    public Result<Object> getVoucherList(@RequestBody QueryOrderVo vo) throws ChanjetApiException {
        GetVoucherResponse getVoucherResponse = chanjetSpi.getOrderList(vo);
        Map<String, Object> data = getVoucherResponse.getData();
        converData(data);
        return Result.OK(data);
    }


    @GetMapping("/getInventoryClass")
    public Result<List> getInventoryClass() throws ChanjetApiException {
        InventoryClassResponse inventoryClass = chanjetSpi.getInventoryClass();
        return Result.OK(inventoryClass);
    }

    private Map<String,Object> converData(Map<String,Object> map){
        List<String> columns = (List<String>) map.get("Columns");
        List<List> rows = (List<List>) map.get("Rows");
        List<JSONObject> list = new ArrayList<>();
        for (List row: rows) {
            JSONObject jsonRow = new JSONObject();
            for (int i = 0; i < row.size(); i++) {
                jsonRow.putOpt(columns.get(i),row.get(i));
            }
            list.add(jsonRow);
        }
        map.put("records",list);
        return map;
    }

    @GetMapping("/addEmsOrder")
    @Log(title = "T+订单录入MES",businessType = BusinessType.INSERT)
    public Result<Object> add2EmsOrder(@RequestParam(name="code") String code) throws ChanjetApiException {
        QueryOrderVo vo = new QueryOrderVo();
        vo.setVourcherCode(code);
        GetVoucherResponse getVoucherResponse = chanjetSpi.getVoucherOrder(vo);
        Map<String, Object> data = getVoucherResponse.getData();
        data.put("createBy",getUsername());
        iMesScalesOrderService.tpToEms(data);
        return Result.OK("执行成功！");
    }


    @GetMapping("/getOrderItem")
    public Result<Object> getOrderItem(@RequestParam(name="code") String code) {
        QueryWrapper<MesScalesOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("product_code", code);
        MesScalesOrderItem one = iMesScalesOrderItemService.getOne(wrapper);
        if (one == null) return Result.ERROR("请先将订单录入EMS");
        return Result.OK(one);
    }

    @PostMapping("/orderItemList")
    public Result<Object> orderItemList(@RequestBody QueryOrderVo vo) throws ChanjetApiException {
        GetVoucherResponse response = chanjetSpi.getOrderItemList(vo);
        Map<String, Object> data = response.getData();
        converData(data);
        return Result.OK();
    }
}